﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace seiacpscs_a2.datastructures.linkedlist
{
    public class LinkedList:DataStructure
    {
        private ListNode first;
        private ListNode last;
        private int length;

        public LinkedList()
        {
            first = null;
            last = null;
            this.length = 0;
        }

        public bool IsEmpty
        {
            get { return first == null; }
        }

        public override void add(int item)
        {

            ListNode listNode = new ListNode(item);

            if (this.IsEmpty)
            {
                first = listNode;
                last = listNode;
                this.length++;
            }
            else
            {
                last.NextNode= listNode;
                last = listNode;
                this.length++;
            }

        }

        
        public override bool contains(int item)
        {
            this.numberOfAccesses = 0;

            bool isFound = false;

            if (!this.IsEmpty)
            {

                ListNode node = first;
                do
                {
                    ++(this.numberOfAccesses);
                    if (node.Item == item)
                    {
                        isFound = true;
                        break;
                    }
                    else
                    {
                        node = node.NextNode;
                    }
                } while (node != null);
            }

            return isFound;
        }

	    public int Length
	    {
		    get { return length;}
	    }

        public ListNode First
        {
            get { return first; }
        }

        public ListNode Last
        {
            get { return last; }
        }

        public override String DataStructureName
        {
            get { return "LinkedList"; }
        }

        public int getItemAt(int index)
        {
            int internalIndex = 0;
            if (index == 0)
            {
                return first.Item;
            }
            else
            {

                ListNode node = first.NextNode;
                internalIndex++;
                while (node != null)
                {
                    if (index == internalIndex)
                    {
                        return node.Item;
                    }
                    else
                    {
                        node = node.NextNode;
                        internalIndex++;
                    }
                }

            }

            return -1;
        }

    }
}
